package net.starwifi.duobao.web;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import net.starwifi.duobao.AppInitListener;
import net.starwifi.duobao.entity.*;
import net.starwifi.duobao.hfg.notify.NotifyRequest;
import net.starwifi.duobao.hfg.notify.NotifyTradeDetail;

import net.starwifi.duobao.hfg.query.QueryResponse;
import net.starwifi.duobao.hfg.refund.RefundResponse;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.plugin.PaymentPlugin;
import net.starwifi.duobao.service.*;
import net.starwifi.duobao.utils.times.DateTool;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller("wapPaymentController")
@RequestMapping("/payment")
public class PaymentController extends BaseController {


    @Autowired
    MemberService memberService;

    @Autowired
    private PluginService pluginService;

    @Autowired
    OrderService orderService;

    @Autowired
    OrderLogService orderLogService;

    @Autowired
    PaymentService paymentService;

    @Autowired
    DBOrderService dbOrderService;


    @Autowired
    SettingService settingService;

    /**
     * 支付跳转
     */
    @ResponseBody
    @RequestMapping(value = "/autoPay", method = RequestMethod.GET)
    public Message paymentReturn(Long id) {
        DBOrder dbOrder = dbOrderService.find(id);
        dbOrderService.payment(dbOrder, null);
        return Message.success("success");
    }


    /**
     * 获取支付签名信息
     */
    @RequestMapping(value = "/submit")
    @ResponseBody
    public Object submit(Long orderId, String paymentPluginId, HttpServletRequest request, HttpServletResponse response) {
        Member member = memberService.getCurrent();
        PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
        if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
            return Message.error("支付插件错误");
        }
        Order order = orderService.find(orderId);
        if (order == null) {
            return Message.error("订单不存在");
        }
        if (order.getOrderStatus() == 1) {
            return Message.error("订单已完成,无法再支付");
        }
        if (order.getOrderStatus() == 2) {
            return Message.error("订单已取消,无法再支付");
        }
        if (order.getPaymentStatus() == 1) {
            return Message.error("订单已支付,无法再继续支付");
        }


        Payment payment = paymentService.findByOrderSn(order.getSn());
        if (payment == null) {
            payment = new Payment();
            payment.setSn(AppInitListener.idGenerate.getID().toString()); //支付流水号码
            payment.setType(Payment.Type.db);
            payment.setMethod(Payment.Method.online);
            payment.setStatus(Payment.Status.wait);
            payment.setPaymentMethod(order.getPaymentMethodName() + Payment.PAYMENT_METHOD_SEPARATOR + paymentPlugin.getPaymentName());
            payment.setFee(order.getFee());
            payment.setAmount(order.getAmount());
            payment.setPaymentPluginId(paymentPluginId);
            payment.setExpire(paymentPlugin.getTimeout() != null ? DateUtils.addMinutes(new Date(), paymentPlugin.getTimeout()) : null);
            payment.setOrderId(orderId);
            payment.setOrderSn(order.getSn());
            paymentService.save(payment);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("requestUrl", paymentPlugin.getRequestUrl());
        result.put("requestMethod", paymentPlugin.getRequestMethod());
        result.put("requestCharset", paymentPlugin.getRequestCharset());
        result.put("parameterMap", paymentPlugin.getParameterMap(payment, order.getProductName(), request));
        if (StringUtils.isNotEmpty(paymentPlugin.getRequestCharset())) {
            response.setContentType("text/html; charset=" + paymentPlugin.getRequestCharset());
        }
        return result;
    }

    /**
     * 支付跳转
     */
    @RequestMapping(value = "/return/{sn}", method = RequestMethod.GET)
    public String paymentReturn(@PathVariable String sn) {
        Payment payment = paymentService.findBySn(sn);
        if (payment != null) {
            if (payment.getType() == Payment.Type.db) {
                return "redirect:/dMember/record";
            } else if (payment.getType() == Payment.Type.recharge) {
                return "redirect:/dMember/chargeRecord";
            }
        }
        return "redirect:/dMember/chargeRecord";
    }

//    /**
//     * 通知
//     */
//    @RequestMapping("/notify/{sn}")
//    @ResponseBody
//    public String notify(@PathVariable String sn, @RequestBody String xmlData, HttpServletRequest request) {
//        Payment payment = paymentService.findBySn(sn);
//        DBOrder dborder = dbOrderService.findBySn(payment.getOrderSn());
//        if (payment != null) {
//            PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(payment.getPaymentPluginId());
//            if (paymentPlugin != null) {
//                if (paymentPlugin.verifyNotify(payment, PaymentPlugin.NotifyMethod.async, xmlData, request)) { //支付成功
//                    paymentService.handle(payment);
//                }
//                return paymentPlugin.getNotifyMessage(payment, PaymentPlugin.NotifyMethod.async, xmlData, request);
//            }
//            return null;
//        }
//        return null;
//    }

//    /**
//     * 通知
//     */
//    @RequestMapping("/notify")
//    @ResponseBody
//    public String notifyReq(@RequestBody String json, HttpServletRequest request, ModelMap model) {
//        NotifyRequest req=new NotifyRequest();
//        req.parseReq(json);
//        NotifyTradeDetail detail=req.getTrade_details().get(0);
//        String sn=detail.getPartner_trade_no();
//        System.out.println("相应订单："+sn);
//        Payment payment = paymentService.findByOrderSn(sn);
//        DBOrder dborder = dbOrderService.findBySn(payment.getOrderSn());
//        if (payment != null) {
//            PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(payment.getPaymentPluginId());
//            if (paymentPlugin != null) {
//                if ("00".equals(detail.getResult_code())) { //支付成功
//                    System.out.print("支付成功；；；；");
//                    paymentService.handle(payment);
//                }
//                return paymentPlugin.getNotifyMessage(payment, PaymentPlugin.NotifyMethod.async,detail, request);
//            }
//            return null;
//        }
//        return null;
//    }




    /**
     * 订单查询
     */
    @ResponseBody
    @RequestMapping(value = "/queryOrder")
    public Message queryOrder(String  sn,HttpServletRequest request){


        Payment payment = paymentService.findByOrderSn(sn);

        if (payment==null){
            return Message.error("订单不存在");
        }
        PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(payment.getPaymentPluginId());
        if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
            return Message.error("支付插件错误");
        }

        QueryResponse res=paymentPlugin.query(payment, request);
        return Message.success(res.getRet_code()+" "+res.getRet_msg());
    }

    /**
     * 手动退款
     */
    @ResponseBody
    @RequestMapping(value = "/refunded")
    public Message refunded(String sn,HttpServletRequest request){
        final Payment payment = paymentService.findByOrderSn(sn);
        if (payment==null){
            return Message.error("订单不存在");
        }
        PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(payment.getPaymentPluginId());
        if (paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
            return Message.error("支付插件错误");
        }
        Refunds refunds=refundsService.findByOrderSn(payment.getOrderSn());
        if(refunds==null){
            refunds=new Refunds();
            refunds.setSn(AppInitListener.idGenerate.getID().toString());
            refunds.setMethod(Refunds.Method.online);
            refunds.setStatus(Refunds.Status.wait);
            refunds.setPaymentMethod(payment.getPaymentMethod());
            refunds.setAmount(payment.getAmount());
            if(payment.getOrderId()!=null){
                refunds.setOrderId(payment.getOrderId());
            }else{
                long orderid = Long.valueOf("100").longValue()+ AppInitListener.idGenerate.getID();
                refunds.setOrderId(orderid);
            }
            refunds.setOrderSn(payment.getOrderSn());
            refunds.setOperator("Tester");
           // refunds.setFlag(payment.getFlag());
            refundsService.save(refunds);
        }

        RefundResponse res = paymentPlugin.refunds(payment.getOrderSn(), request);
        if (res.getRet_code().equals("00")){
            String ordersn = res.getPartner_trade_no();
           DBOrder dborder = dbOrderService.findBySn(ordersn);
            dbOrderService.refunds(dborder, refunds);
           // tradeRecordService.refunds(payment.getMemberId(),payment.getAmount(),"1元夺宝退款",payment.getOrderSn()); //订单退款
            System.out.println("1元夺宝退款");
        }
        return Message.error(res.getRet_code()+" "+ res.getRet_msg());

    }
//
//    /**
//     * 生成文件
//     */
//    @RequestMapping("/push")
//    @ResponseBody
//    public void push() {
//        try {
//            String path = "/home/www/file/";
//            String fileName = "P_AUDIT_DATA_" + getDate() + ".txt";
//            File file = new File(path + fileName);
//           paymentService.exportTxtFile(file);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

//    /**
//     * 上传
//     */
//    @RequestMapping("/upload")
//    @ResponseBody
//    public void upload() {
//        try {
//            String path = "/home/www/file/";
//            String fileName = "P_AUDIT_DATA_" + getDate() + ".txt";
//            File file = new File(path + fileName);
//            fileService.upload(file);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (SftpException e) {
//            e.printStackTrace();
//        } catch (JSchException e) {
//            e.printStackTrace();
//        }
//    }

    private String getDate(){
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = DateTool.addDays(new Date(), 0);
        return  format.format(date);
    }
    @Autowired
    RefundsService refundsService;

    @Autowired
    TradeRecordService tradeRecordService;
    @Autowired
    FileService fileService;


}
